package com.whq.websocket;

import java.io.IOException;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
public class SystemWebSocketHandler implements WebSocketHandler{
	private static final Logger logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	

	private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

	//连接关闭后处理
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1) throws Exception {
		  logger.info("websocket connection closed......");
		  users.remove(session);
	}

	//连接建立后处理
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		users.add(session);
		logger.info("connect to the websocket success......");
		//session.sendMessage(new TextMessage("connect to the websocket success"));
	}

	//接收文本消息，并发送出去
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
//		logger.info("客户端发给server的消息是：======="+message.toString());
//
//		session.sendMessage(new TextMessage("this  is a websocket message"));
//		sendMessageToUsers(new TextMessage("this  is a websocket message"));
	}

	//抛出异常时处理
	@Override
	public void handleTransportError(WebSocketSession session, Throwable arg1) throws Exception {
		  logger.info("websocket connection closed......");
		  users.remove(session);
		  if(session.isOpen()){
	            session.close();
	       }
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
    /**
     * 给某个用户(webSocket 的链接 )发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
		this.logger.info("<sendMessageToUser>调用 webSocket 通知前端");
        for (WebSocketSession user : users) {
            if (user.getAttributes().containsKey(userName) && user.getAttributes().get(userName).equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                        logger.info("给用户：》》》"+userName+"发送了消息：》》》》》"+message.getPayload());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
